package de.uni_mannheim.informatik.ai.dame_ai.util;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;




/**
 * A lightweight Swing component that allows to display another Component which is added to it
 * with a certain padding.
 * @author Martin Boelle
 *
 */
@SuppressWarnings("serial")
public class PaddedPanel extends JPanel{

	private Component content;
	private int hGap=0;
	private int vGap=0;
	private BufferedImage bgImage;
	
	public PaddedPanel(Component content, int hGap, int vGap) {
		this(content, hGap, vGap, null);
	}
	
	public PaddedPanel(Component content, int hGap, int vGap, BufferedImage bgImage) {
		setLayout(null);
		this.content=content;
		this.hGap=hGap;
		this.vGap=vGap;
		this.bgImage=bgImage;
		Dimension contPrefSize=content.getPreferredSize();
		Dimension prefSize= new Dimension(contPrefSize.width+2*hGap, contPrefSize.height+2*vGap);
		System.out.println(prefSize);
		setPreferredSize(prefSize);
		resizeContent();
		add(content);
		addComponentListener(new resizeListener());
	}
	
	
	@Override
	public void paint(Graphics g){
		super.paint(g);
		if(bgImage!=null){
			int repeatFactorX=(int)Math.ceil((float)this.getWidth()/bgImage.getWidth());
			int repeatFactorY=(int)Math.ceil((float)this.getHeight()/bgImage.getHeight());
			int underEdge = this.getHeight()-bgImage.getHeight();
			int righternEdge = this.getWidth()-bgImage.getWidth();
			for(int i=0; i<repeatFactorX; i++){
				g.drawImage(bgImage,i*bgImage.getWidth(), 0, null );
				g.drawImage(bgImage,i*bgImage.getWidth(), underEdge, null );
			}
			for(int i=0; i<repeatFactorY; i++){
				g.drawImage(bgImage,0, i*bgImage.getHeight(), null );
				g.drawImage(bgImage, righternEdge, i*bgImage.getHeight(), null );
			}
		}
	}
	
	public void resizeContent(){
		content.setBounds(hGap, vGap, getWidth()-2*hGap, getHeight()-2*vGap);
	}
	
	@Override
	public Component add(Component comp){
		this.content=comp;
		return super.add(comp);
	}
	
	class resizeListener extends ComponentAdapter{
		@Override
		public void componentResized(ComponentEvent e) {
			super.componentResized(e);
			resizeContent();
		}
	}
}
